package com.ayoka.utils;


import android.os.Handler;
import android.os.Looper;

import java.util.Observable;

/**
 * 倒计时通知事件，上层界面可以订阅此事件
 */
public class CountDownEvent extends Observable {


    private volatile static CountDownEvent instance;

    private long millisInFuture; // 目标结束时的毫秒值  在获取系统的毫秒值后添加需要倒计时的毫秒值
    private Handler handler;

    private CountDownEvent(){
        handler = new Handler(Looper.getMainLooper());
    }

    public static CountDownEvent getInstance(){
        if (instance == null) {
            synchronized (CountDownEvent.class) {
                if (instance == null) {
                    instance = new CountDownEvent();
                }
            }
        }
        return instance;
    }

    /**
      * 开始
     */
    public void start(long millisInFuture){
        this.millisInFuture = millisInFuture + System.currentTimeMillis();
        cancel();
        handler.post(task);
    }

    /**
     * 取消
     */
    public void cancel(){
        handler.removeCallbacks(task);
    }

    /**
     * 清理消息监听
     */
    public void destroy(){
        cancel();
        deleteObservers();
        instance = null;
    }


    private Runnable task = new Runnable() {
        @Override
        public void run() {
            long leftMills = millisInFuture - System.currentTimeMillis();
            setChanged();
            notifyObservers(leftMills);
            if (leftMills > 0){
                handler.postDelayed(this, 1000);
            } else {
                cancel();
            }
        }
    };

}
